package com.eblacorp.archive.util.scanning;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Set;

import org.reflections.Reflections;

import com.eblacorp.archive.annotations.*;



public class ClassScanner {
	
	private String packagePrefix;
	private ArchiveEntityRepository archiveEntityRepository;
	
	public void init(){
		Property property = null;
		String classSymbolicName = null;
		
		Reflections reflections = new Reflections(packagePrefix);
		Set<Class<? extends Object>> documentClasses =  reflections.getTypesAnnotatedWith(DocumentClass.class);
		
		Iterator<Class<? extends Object>> itr = documentClasses.iterator();
		
		while(itr.hasNext()){
			Class<? extends Object> clazz = itr.next();
			if(clazz.isAnnotationPresent(DocumentClass.class)){
				DocumentClass documentClass = clazz.getAnnotation(DocumentClass.class);
				classSymbolicName = documentClass.symbolicName();
				archiveEntityRepository.addEntity(classSymbolicName, clazz);
				
				for(Field field : clazz.getDeclaredFields()){
					if(field.isAnnotationPresent(Property.class)){
						property = field.getAnnotation(Property.class);
						archiveEntityRepository.addProperty(classSymbolicName, property.symbolicName(), field);
					}
				}
				
				for(Field field : clazz.getSuperclass().getDeclaredFields()){
					if(field.isAnnotationPresent(Property.class)){
						property = field.getAnnotation(Property.class);
						archiveEntityRepository.addProperty(classSymbolicName, property.symbolicName(), field);
					}
				}
			}
		}
	}
	
	
	public ArchiveEntityRepository getArchiveEntityRepository() {
		return archiveEntityRepository;
	}

	public void setArchiveEntityRepository(
			ArchiveEntityRepository archiveEntityRepository) {
		this.archiveEntityRepository = archiveEntityRepository;
	}

	public String getPackagePrefix() {
		return packagePrefix;
	}

	public void setPackagePrefix(String packagePrefix) {
		this.packagePrefix = packagePrefix;
	}
}
